package com.shengqin.utils;

import lombok.Data;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Component
@Data
public class FaceDataWriter {

    @Resource
    private FileStorageService fileStorageService;

    public String generateMD5(String faceData,String featureVersion,int picFeatureLen) throws NoSuchAlgorithmException {
        String combinedData = faceData + featureVersion + picFeatureLen;
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] digest = md.digest(combinedData.getBytes());
        
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public String writeFaceData(String faceData,String featureVersion,int picFeatureLen) throws IOException, NoSuchAlgorithmException {
        String md5FileName = generateMD5(faceData,featureVersion,picFeatureLen) + ".txt";
        File outputFile = new File(md5FileName);
        try (FileWriter writer = new FileWriter(outputFile)) {
            writer.write(faceData);
        }
        FileInfo fileInfo = fileStorageService.of(outputFile).setSaveFilename(md5FileName).upload();
        if(outputFile.exists()){
            outputFile.delete();
        }
        return fileInfo.getUrl();
    }
}
